﻿using Common.Entity;
using Sunny.UI;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Windows.Forms;

namespace Common
{
    public partial class UpdateForm : UIForm
    {
        public UpdateForm()
        {
            InitializeComponent();
        }
        private WebClient client;
        private string savepath;

        private void UpdateForm_Load(object sender, EventArgs e)
        {
            try
            {
                UpData downentity = (UpData)this.Tag;


                using (client = new WebClient())
                {
                    //下载完文件触发此事件
                    client.DownloadFileCompleted += Client_DownloadFileCompleted;
                    // 异步下载文件并设置进度条
                    client.DownloadProgressChanged += Client_DownloadProgressChanged;

                    savepath = Application.StartupPath + "\\" + downentity.downName;

                    client.DownloadFileAsync(new Uri(downentity.Updownurl), savepath);
                    //MessageBox.Show("文件下载完成！");

                }
            }
            catch (Exception ex)
            {
                ShowErrorNotifier(ex.Message, true, 5000);
                this.Close();
            }
        }

        private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
        {
            try
            {
                //下载文件的总大小
                double total = e.TotalBytesToReceive;
                //已经下载的大小
                double downloaded = e.BytesReceived;
                downRoundProcess.Value = Convert.ToInt32((downloaded / total) * 100);
            }
            catch (Exception ex)
            {
                // 取消下载操作
                client.CancelAsync();
                ShowErrorNotifier(ex.Message, true, 5000);

            }
        }

        private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null && client.IsBusy == false)
                {
                    ShowSuccessNotifier("下载成功", true, 2000);
                    this.Close();
                    Process currentProcess = Process.GetCurrentProcess();
                    int processID = currentProcess.Id;
                    ///获取正在运行程序的路径
                    string exePathWithFileName = Path.Combine(Application.StartupPath, Path.GetFileName(Application.ExecutablePath));

                    //Process.Start("cmd.exe", $"/c taskkill /f /pid {processID} && timeout 0.1 & del /f /q " + exePathWithFileName);



                    ProcessStartInfo psi = new ProcessStartInfo();
                    psi.FileName = "cmd.exe";
                    psi.Arguments = $"/c taskkill /f /pid {processID} && timeout 0.1 & del /f /q " + exePathWithFileName + $" & start {savepath}";
                    psi.CreateNoWindow = true;
                    psi.UseShellExecute = false;

                    // 执行命令
                    using (Process process = new Process())
                    {
                        process.StartInfo = psi;
                        process.Start();
                    }
                }
                else if (e.Error != null)
                {

                    ShowErrorTip("已取消下载", 2000, true);
                    ////删除已下载的残缺文件
                    if (File.Exists(savepath))
                    {
                        File.Delete(savepath);
                    }
                    this.Close();
                }

            }
            catch (Exception ex)
            {
                ShowErrorNotifier(ex.Message, true, 5000);

            }
        }

        /// <summary>
        /// 取消下载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiButton1_Click(object sender, EventArgs e)
        {
            try
            {
                // 取消下载
                client.CancelAsync();



            }
            catch (Exception ex)
            {
                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }
        /// <summary>
        /// 关闭页面
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UpdateForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                // 取消下载
                client.CancelAsync();



            }
            catch (Exception ex)
            {
                ShowErrorNotifier(ex.Message, true, 5000);
            }
        }
    }
}
